package cn.chenxinjie.hrm.service.impl;

import cn.chenxinjie.hrm.constant.TenantConstant;
import cn.chenxinjie.hrm.domain.Employee;
import cn.chenxinjie.hrm.domain.LoginUser;
import cn.chenxinjie.hrm.domain.Tenant;
import cn.chenxinjie.hrm.dto.TenantRegDto;
import cn.chenxinjie.hrm.feign.LoginUserFeign;
import cn.chenxinjie.hrm.mapper.EmployeeMapper;
import cn.chenxinjie.hrm.mapper.TenantMapper;
import cn.chenxinjie.hrm.query.TenantQuery;
import cn.chenxinjie.hrm.service.ITenantService;
import cn.chenxinjie.hrm.util.AjaxResult;
import cn.chenxinjie.hrm.util.PageList;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 *  服务实现类
 *
 * @author chenxinjie
 * @since 2022-03-09
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private TenantMapper tenantMapper;
    @Autowired
    private LoginUserFeign loginUserFeign;
    @Autowired
    private EmployeeMapper employeeMapper;

    @GlobalTransactional(rollbackFor = Exception.class) // 开启全局异常
    @Override
    public void entering(TenantRegDto tenantRegDto) {
        Employee employee = tenantRegDto.getEmployee();
        Tenant tenant = tenantRegDto.getTenant();
        Long mealId = tenantRegDto.getMealId();
        // 先保存t_login_user,返回主键,再把主键给到t_employee作为外键
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(employee.getUsername());
        loginUser.setPassword(employee.getPassword());
        loginUser.setMealId(mealId);
        loginUser.setType(5);
        AjaxResult result = loginUserFeign.entering(loginUser);
        if (result.isSuccess()) {
            // 如果返回成功,再保存t_employee,返回主键,再把主键给到t_tenant作为外键
            Integer loginId = (Integer) result.getResultObj();
            employee.setLoginId(Long.valueOf(loginId));
            Date date = new Date();
            employee.setInputTime(date);
            employee.setState(TenantConstant.EMPLOYEE_STATE_NORMAL);
            employee.setType(TenantConstant.EMPLOYEE_TYPE_TENANT_ADMIN);
            employeeMapper.insert(employee);
            // 再保存t_tenant
            tenant.setRegisterTime(date);
            tenant.setAdminId(employee.getId());
            tenant.setState(TenantConstant.TENANT_CHECK_WAIT);
            tenantMapper.insert(tenant);
        }

    }

    @Override
    public PageList<Tenant> getTenantPage(TenantQuery query) {
        Page<Tenant> page = new Page<>(query.getPage(), query.getRows());
        List<Tenant> list = tenantMapper.getTenantPage(page, query);
        return new PageList<Tenant>(page.getTotal(),list);
    }
}
